package cn.cttic.resource.controller;


import cn.cttic.common.core.constant.CacheConstants;
import cn.cttic.link.api.RemoteThirdSmsService;
import cn.cttic.resource.api.domain.RemoteSms;
import cn.hutool.core.util.RandomUtil;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import cn.cttic.common.core.constant.Constants;
import cn.cttic.common.core.constant.GlobalConstants;
import cn.cttic.common.core.domain.R;
import cn.cttic.common.ratelimiter.annotation.RateLimiter;
import cn.cttic.common.redis.utils.RedisUtils;
import cn.cttic.common.web.core.BaseController;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.LinkedHashMap;

/**
 * 短信功能
 *
 * @author Times.Studio
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/sms")
public class SysSmsController extends BaseController {

    @DubboReference
    RemoteThirdSmsService remoteThirdSmsService;

    /**
     * 短信验证码
     *
     * @param phonenumber 用户手机号
     */
    @RateLimiter(key = "#phonenumber", time = 60, count = 1)
    @GetMapping("/code")
    public R<Void> smsCaptcha(@NotBlank(message = "{user.phonenumber.not.blank}") String phonenumber) {
        String key = CacheConstants.CAPTCHA_CODE_KEY + phonenumber;
        String code = RandomUtil.randomNumbers(4);
        RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));

        RemoteSms smsResponse = remoteThirdSmsService.sendSaleCustomerVerifyCode(phonenumber, code);

        if (!smsResponse.getSuccess()) {
            log.error("验证码短信发送异常 => {}", smsResponse);
            return R.fail(smsResponse.getResponse().toString());
        }
        return R.ok();
    }

}
